package cn.cvs.controller;

import cn.cvs.pojo.Contact;
import cn.cvs.service.ContactService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@RequestMapping("/contact")
@Controller
public class ContactController {
    @Autowired
    private ContactService service;
    @RequestMapping("/list")
    public String list(Model model,@RequestParam(required = false,defaultValue = "") String cname,
                       @RequestParam(defaultValue = "1") Integer pageIndex,@RequestParam(defaultValue = "3") Integer pageSize
    ){
        List<Contact> list = service.list(cname,pageIndex,pageSize);
        Integer pageCount = service.pageCount(cname, pageSize);
        model.addAttribute("list",list);
        model.addAttribute("pageIndex",pageIndex);
        model.addAttribute("pageCount",pageCount);
        model.addAttribute("cname",cname);
        return "../../index";
    }
    @RequestMapping("/add")
    public String add(HttpServletRequest request, Contact contact){
        int r = service.add(contact);
        String msg = "添加成功！";
        if (r < 0){
            msg = "添加失败！";
        }
        HttpSession session = request.getSession();
        session.setAttribute("msg",msg);
        if (r > 0)
            return  "redirect:/contact/list";
        else
            return "../../add";
    }
    @RequestMapping("/{id}/getContact")
    public String getContact(@PathVariable Integer id,Model model){
        Contact contact = service.getContact(id);
        model.addAttribute("contact",contact);
        return "../../update";
    }
    @RequestMapping("/update")
    public String update(HttpServletRequest request, Contact contact){
        int r = service.update(contact);
        String msg = "更新成功！";
        if (r < 0){
            msg = "更新失败！";
        }
        HttpSession session = request.getSession();
        session.setAttribute("msg",msg);
        if (r > 0)
            return  "redirect:/contact/list";
        else
            return "../../update";
    }
    @ResponseBody
    @RequestMapping("/del")
    public Object del(Integer id){
        int r = service.del(id);
        return JSON.toJSONString(r);
    }
}
